# -*- coding: utf-8 -*-

# TODO: remove python agent attribute from header

import urllib,urllib2

from mhd.models import MHD_Stop_Type, MHD_Link, MHD_Stop, MHD_Link_Stop
from mhd.parser import MHD_LinkStopListParser

url = 'http://www.imhd.zoznam.sk/ba/index.php'

for mhd_link in MHD_Link.objects.all():    
    print "routing link %s" % mhd_link
    
    parameters = {'x':10, 'y':12, 'hladaj':mhd_link.name, 'w':'212b2e292cef2f302523ea'}    
    data = urllib.urlencode(parameters)
    request = urllib2.Request(url, data)
    response = urllib2.urlopen(request)
    
    mhd_link_stop_list_parser = MHD_LinkStopListParser()
    (stops_route_a, stops_route_b) = mhd_link_stop_list_parser.parse(response.read().decode('cp1250'))
    
    stop_num = 1
    for stop in stops_route_a:
        mhd_stops = MHD_Stop.objects.filter(name = stop)
        mhd_stop = None
        if not mhd_stops:
            print "stop %s not found, adding" % stop
            mhd_stop_type = MHD_Stop_Type.objects.get(id = 1)            
            mhd_stop = MHD_Stop(name = stop, lat = 0.0, lng = 0.0, stop_type = mhd_stop_type)
            mhd_stop.save()
        else:        
            mhd_stop = mhd_stops[0]
        
        mhd_link_stops = MHD_Link_Stop.objects.filter(link = mhd_link, stop = mhd_stop)
        mhd_link_stop = None
        if not mhd_link_stops:
            print "link %s does not stop at %s, adding association" % (mhd_link, mhd_stop)
            mhd_link_stop = MHD_Link_Stop(link = mhd_link, stop = mhd_stop, route_a_num = stop_num)
        else:        
            mhd_link_stop = mhd_link_stops[0]
            mhd_link_stop.route_a_num = stop_num
        mhd_link_stop.save()
        
        stop_num = stop_num + 1
            
    stop_num = 1
    for stop in stops_route_b:
        mhd_stops = MHD_Stop.objects.filter(name = stop)
        mhd_stop = None
        if not mhd_stops:
            print "stop %s not found, adding" % stop
            mhd_stop_type = MHD_Stop_Type.objects.get(id = 1)                    
            mhd_stop = MHD_Stop(name = stop, lat = 0.0, lng = 0.0, stop_type = mhd_stop_type)
            mhd_stop.save()
        else:        
            mhd_stop = mhd_stops[0]
        
        mhd_link_stops = MHD_Link_Stop.objects.filter(link = mhd_link, stop = mhd_stop)
        mhd_link_stop = None
        if not mhd_link_stops:
            print "link %s does not stop at %s, adding association" % (mhd_link, mhd_stop)
            mhd_link_stop = MHD_Link_Stop(link = mhd_link, stop = mhd_stop, route_b_num = stop_num)
        else:        
            mhd_link_stop = mhd_link_stops[0]
            mhd_link_stop.route_b_num = stop_num
        mhd_link_stop.save()
        
        stop_num = stop_num + 1